package cn.flying.cloud.gateway.oauth.handler;

import java.nio.charset.StandardCharsets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import reactor.core.publisher.Mono;

import cn.flying.cloud.base.common.enums.RtCodeEnum;
import cn.flying.cloud.base.common.vo.Rt;

/**
 * 自定义返回结果：处理没有登录、token过期时、认证失败
 *
 * @author: admin
 * @date: 2023年06月26日 10:23
 * @version: 1.0
 */
@Component
public class RequestAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
        logger.error("系统认证异常", e);
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        String body;
        if (e instanceof InvalidBearerTokenException) {
            //返回无效的用户Token凭证
            body = JSON.toJSONString(Rt.error(RtCodeEnum.R10005), JSONWriter.Feature.WriteMapNullValue);
        } else {
            body = JSON.toJSONString(Rt.error(RtCodeEnum.R10020), JSONWriter.Feature.WriteMapNullValue);
        }
        DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }
}